package main

import (
	"net"
	"net/url"
	"os"
	"strings"
)

func main() {
	// 检查必要的参数
	if len(os.Args) < 2 {
		usage()
	}
	// 解析请求的 URL
	u, err := url.Parse(os.Args[1])
	if err != nil {
		werr(err, "invalid url")
	}

	// 构建远程地址
	host := strings.TrimSpace(u.Host)
	if len(os.Args) >= 3 {
		host = strings.TrimSpace(os.Args[2])
	}
	wout("Lookup Host: %s", host)
	addr, err := parseAddr(host, u.Scheme)
	if err != nil {
		werr(err, "lookup failed")
	}

	// 连接远程服务器
	wout("Trying %s (%s:%d) ...", u.Host, addr.IP, addr.Port)
	var conn net.Conn
	conn, err = net.DialTCP("tcp", nil, addr)
	if err != nil {
		werr(err, "connect failed")
	}
	defer conn.Close()
	wout("Connected to %s (%s:%d)", u.Host, addr.IP, addr.Port)

	// 握手 TLS
	if isHttps(u.Scheme) {
		wout("Trying TLS handshake ...")
		if conn, err = tlsConnect(conn.(*net.TCPConn), u.Hostname()); err != nil {
			werr(err, "connect ssl failed")
		}
		wout("TLS handshake Done!")
	}

	// 发起请求，读取响应
	rwc := make(chan struct{})
	rrc := make(chan struct{})
	go doGetRequest(conn, u, rwc)
	go receiveResponse(conn, rrc)
	<-rwc
	<-rrc
}
